package com.calcium.capiprovicerclient;


import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.calcium.capiprovicerclient.model.UserApiKeys;

import java.util.HashMap;
import java.util.Map;


public class CapiProvider {

    /**
     * apiKey对象
     */
    private final UserApiKeys apiKeys;

    protected CapiProvider() {
        this.apiKeys = new UserApiKeys();
    }

    /**
     * get通用方法
     * @param url 请求地址
     * @return HttpRequest
     */
    public HttpResponse get(String url) {
        Map<String,String> headers = new HashMap<>();
        signHeaders(headers);
        return HttpRequest.get(url).addHeaders(headers).execute();
    }

    /**
     * post通用方法
     * @param url 请求地址
     * @return HttpRequest
     */
    public HttpResponse post(String url) {
        Map<String,String> headers = new HashMap<>();
        signHeaders(headers);
        return HttpRequest.post(url).addHeaders(headers).execute();
    }

    /**
     * 带有自定义请求头的get请求
     * @param url 请求地址
     * @param headers 自定义请求头
     * @return HttpRequest
     */
    public HttpResponse get(String url, Map<String,String> headers) {
        signHeaders(headers);
        return HttpRequest.get(url).addHeaders(headers).execute();
    }

    /**
     * 带有自定义请求头的post请求
     * @param url 请求地址
     * @param headers 自定义请求头
     * @return HttpRequest
     */
    public HttpResponse post(String url,Map<String,String> headers) {
        signHeaders(headers);
        return HttpRequest.post(url).addHeaders(headers).execute();
    }

    /**
     * 带有自定义请求头和请求体的post请求
     * @param url 请求地址
     * @param headers 自定义请求头
     * @param body 请求体
     * @return HttpRequest
     */
    public HttpResponse post(String url,Map<String,String> headers,String body) {
        signHeaders(headers);
        return HttpRequest.post(url).body(body).addHeaders(headers).execute();
    }

    /**
     * post请求
     * @param url 请求地址
     * @param body 请求体
     * @return HttpRequest
     */
    public HttpResponse post(String url,String body) {
        Map<String,String> headers = new HashMap<>();
        signHeaders(headers);
        return HttpRequest.post(url).body(body).addHeaders(headers).execute();
    }

    /**
     * 生成签名
     * @param headers 请求头
     */
    private void signHeaders(Map<String,String> headers) {
        String timeStamp = String.valueOf(System.currentTimeMillis());
        String nonce = UUID.fastUUID().toString(true);
        String signature = SecureUtil.md5(apiKeys.getAccessKey() + apiKeys.getSecretKey() + timeStamp);
        headers.put("Nonce", nonce);
        headers.put("TimeStamp", timeStamp);
        headers.put("AccessKey", apiKeys.getAccessKey());
        headers.put("Signature",signature);
    }
}
